package com.example.smartcity.logic.net_work

import com.example.smartcity.logic.net_work.SmartCityResponse.create
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * 处理网络回调
 */
object Response {
    private val api = create<ServiceApi>()

    // 获取主页轮播图
    suspend fun getSlideshow(map: Map<String, Int>) = api.getSlideshow(map).await()

    // 获取主页全部服务
    suspend fun getMore(Is: String) = api.getMore(Is).await()

    // 获取主页热门主题
    suspend fun getNewS(str: String) = api.getNewSEntity(str).await()

    // 获取主页热门主题
    suspend fun getNewSEntityType(str: Int) = api.getNewSEntityType(str).await()

    // 获取新闻专栏
    suspend fun getNewSTitle() = api.getNewsTitle().await()

    // 获取全部新闻
    suspend fun getNewsAll() = api.getNewSEntityAll().await()

    // 登录请求
    suspend fun getLogin(body: RequestBody) = api.getLogin(body).await()

    // 用户全部信息
    suspend fun getLoginAll(token: String) = api.getLoginAll(token).await()

    // 用户注册
    suspend fun getRegister(body: RequestBody) = api.getRegister(body).await()

    // 修改用户信息
    suspend fun getModification(token: String, body: RequestBody) = api.getModification(token, body).await()

    // 修改密码
    suspend fun getLoginPwd(token: String, body: RequestBody) = api.getLoginPwd(token, body).await()

    // 反馈意见
    suspend fun getFeedBack(token: String, body: RequestBody) = api.getFeedBack(token, body).await()

    // 获取反馈列表
    suspend fun getFeedBackAll(token: String) = api.getFeedBackAll(token).await()

    // 获取新闻评论列表
    suspend fun getComment() = api.getComments().await()

    // 获取新闻详细内容
    suspend fun getCommentAll(id: Int) = api.getCommentAll(id).await()

    // 发表新闻评论
    suspend fun setComment(token: String, body: RequestBody) = api.setComment(token, body).await()


    private suspend fun <T> Call<T>.await() : T{
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    // 不为空将数据传输过去
                    if(body != null) continuation.resume(body)
                    else continuation.resumeWithException(
                        RuntimeException("网络请求失败！")
                    )
                }

                override fun onFailure(call: Call<T>, throwable: Throwable) {
                    continuation.resumeWithException(throwable)
                }

            })
        }
    }


}